﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace daonaite.core.Catche
{
    /// <summary>
    /// redis缓存
    /// </summary>
    public class RedisCache : ICacheHelp
    {

        public ConnectionMultiplexer Redis { get; set; }
        public RedisCache(string connection)
        {
            Redis = ConnectionMultiplexer.Connect(connection);
        }


        public T? get<T>(string key, int databse = 0)
        {

            var Db = Redis.GetDatabase(databse);
            string? content = Db.StringGet(key);
            if (content == null)
            {
                return default;
            }
            return JsonSerializer.Deserialize<T>(content);
        }

        public int listcount(string key, int databse = 0)
        {
            var Db = Redis.GetDatabase(databse);
            return (int)Db.ListLength(key);
        }

        public T? listleftPop<T>(string key, int databse = 0)
        {
            var Db = Redis.GetDatabase(databse);
            var val = Db.ListLeftPop(key);
            if (!val.HasValue)
            {
                return default;
            }
            return JsonSerializer.Deserialize<T>(val!);
        }

        public void listleftPush<T>(string key, T data, int databse = 0)
        {
            var Db = Redis.GetDatabase(databse);
            Db.ListLeftPush(key, JsonSerializer.Serialize<T>(data));
        }

        public T? listrightPop<T>(string key, int databse = 0)
        {
            var Db = Redis.GetDatabase(databse);
            var val = Db.ListRightPop(key);
            if (!val.HasValue)
            {
                return default;
            }
            return JsonSerializer.Deserialize<T>(val!);
        }

        public void listrightPush<T>(string key, T data, int databse = 0)
        {
            var Db = Redis.GetDatabase(databse);
            Db.ListRightPush(key, JsonSerializer.Serialize<T>(data));
        }

        public void remove(string key, int databse = 0)
        {
            var Db = Redis.GetDatabase(databse);
            Db.KeyDelete(key);
        }

        public void set<T>(string key, T data, int databse = 0)
        {
            var Db = Redis.GetDatabase(databse);
            Db.StringSet(key, JsonSerializer.Serialize<T>(data));
        }

        public void set<T>(string key, T data, int ExpirationTime, int databse = 0)
        {
            var Db = Redis.GetDatabase(databse);
            Db.StringSet(key, JsonSerializer.Serialize<T>(data), TimeSpan.FromSeconds(ExpirationTime));
        }
    }
}
